package alit.generator.bl.populator;

import alit.generator.bl.generator.Context;

import java.util.Random;

/**
 * User: Alexander Litvinenko
 * Date: 11/19/11
 * Time: 12:20 PM
 */
public abstract class PopulatorKit {

    private static Random random = new Random();

    protected static Random getRandom() {
        return random;
    }

    public static class NullPopulator implements IPopulator {
        public static String getId() {
            return "null";
        }

        public String populate(Context context) {
            return "NULL";
        }
    }

    public static class FromSourcePopulator implements IPopulator {

        public static final String VAR_INSERT = "{@ins}";
        private boolean random;
        private String wrap;
        private String[] sourceArr;
        private int count = 0;

        public FromSourcePopulator(String source, String separator, boolean isRandom, String wrap) {
            if (source == null)
                throw new PopulatorException("Source is empty!");
            random = isRandom;
            this.wrap = wrap;
            sourceArr = source.split(separator);
        }

        public static String getId() {
            return "fromSource";
        }

        public String populate(Context context) {
            if (random)
                return populateRandomly();
            return populateSequentially();
        }

        private String populateSequentially() {
            if (count >= sourceArr.length) count = 0;
            if (wrap.isEmpty())
                return sourceArr[count++];
            return wrap.replace(VAR_INSERT, sourceArr[count++]);
        }

        private String populateRandomly() {
            if (wrap.isEmpty())
                return sourceArr[getRandom().nextInt(sourceArr.length)];
            return wrap.replace(VAR_INSERT, sourceArr[getRandom().nextInt(sourceArr.length)]);
        }
    }

    public abstract String getSqlDialect();

    public abstract String getTypeName();

    @Override
    public String toString() {
        return getSqlDialect() + " " + getTypeName();
    }
}